package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    GreeTextScan greeTextScan;

    @Autowired
    GreenImageScan greenImageScan;

    @Value("${file.oss.web-site}")
    private String webSite;

    //自媒体文章自动审核
    @Override
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        //参数校验
        if (wmNewsId==null){
            log.error("当前的审核id空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            return;
        }
        //1 根据WmNes文章id查询文章
        WmNews wmNews = wemediaFeign.findById(wmNewsId);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
            log.error("审核的自媒体文章不存在，自媒体的id:{}", wmNewsId);
            return;
        }
        //判断文章的状态
        //2 文章状态=4 人工审核通过，直接保存文章
        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode())&&wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            //保存数据
            saveAppArticle(wmNews);
            return;
        }
        //3 文章状态=8 审核通过 但是发布时间小于等于当前时间，直接保存文章
        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode())&&wmNews.getPublishTime().getTime() <= System.currentTimeMillis()){
            //保存数据
            saveAppArticle(wmNews);
            return;
        }
        //4 文章状态=1 待审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            // 抽取文章内容中的文本和图片
            Map<String, Object>contentAndImagesResult=handleTextAndImages(wmNews);

            // 4.1 自管理敏感词审核
            // 4.2 阿里云审核文本内容
            boolean isTextScan = handleTextScan((String) contentAndImagesResult.get("content"), wmNews);
            if (!isTextScan) return;
            // 4.3 阿里云图片审核
            boolean isImageScan = handleImagesScan((List) contentAndImagesResult.get("images"), wmNews);
            if (!isImageScan) return;
            //TODO 4.4 判断文章发布时间大于当前时间，修改状态8


            //TODO 5 保存文章相关数据

            //TODO 6 同步索引库
        }
    }

    //图片审核-阿里云
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        // 无图则无需审核
        if (images==null||images.size() == 0){
            return true;
        }
        boolean flag =true;
        try {
            images=images.stream().distinct().collect(Collectors.toList());
            Map map = greenImageScan.imageUrlScan(images);
            //审核不通过
            if (map.get("suggestion").equals("block")){
                updateWmNews(wmNews, (short) 2, "文章图片有违规");
                flag = false;
            }
            //人工审核
            if (map.get("suggestion").equals("block")) {
                updateWmNews(wmNews, (short) 2, "文章图片有违规");
                flag = false;
            }
            //人工审核
            if (map.get("suggestion").equals("review")) {
                updateWmNews(wmNews, (short) 3, "文章图片有不确定元素");
                flag = false;
            }
        }catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, (short) 3, "阿里云审核失败，转入人工审核");
            flag = false;
        }
        return flag;
    }


    //审核文内容-阿里云
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag=true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            //审核不通过
            if (map.get("suggestion").equals("block")){
                flag = false;
                updateWmNews(wmNews, (short) 2, "文本中内容有敏感词汇");
            }
            //需要人工审核
            if (map.get("suggestion").equals("review")){
                flag = false;
                updateWmNews(wmNews, (short) 3, "文本中内容需要人工审核");
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("文章阿里云内容审核失败，转入人工审核, e：{}",e);
            updateWmNews(wmNews, (short) 3, "文章阿里云内容审核失败,转入需要人工审核");
        }
        return flag;
    }

    //修改文章
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.getCode().equals(0)) {
            CustException.cust(AppHttpCodeEnum.WEMEDIA_UPDATE_ERROR);
        }
    }

    //抽取文章内容中的文本和图片
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        // // 抽取文章文本
        String content = wmNews.getContent();
        List<Map> contentList = JSON.parseArray(content, Map.class);
        // 接收文本
        StringBuilder contents = new StringBuilder();
        // 文章标题 审核？
        // 接收图片列表
        List<String> imageList = new ArrayList<>();

        for (Map<String, String>map : contentList){
            if (map.get("type").equals("text")){
                contents.append(map.get("value"));
            }
            if (map.get("type").equals("image")) {
                imageList.add(map.get("value"));
            }
        }
        // 解析文章封面的图片(注意文章封面地址没有前缀)
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] splits=wmNews.getImages().split(",");
            for (String url : splits){
                imageList.add(webSite+url);
            }
        }
        //返回结果
        Map<String, Object> map = new HashMap<>();
        resultMap.put("content", contents.toString());
        resultMap.put("images", imageList);
        return resultMap;
    }

    //保存APP端文章相关数据
    private void saveAppArticle(WmNews wmNews) {

        //保存app相关文章
        ResponseResult responseResult = saveArticle(wmNews);
        if (!responseResult.getCode().equals(0)){
            throw new RuntimeException("文章审核保存app文章失败");
        }
        Object data = responseResult.getData();
        //修改自媒体文章状态，状态为9  审核通过
        wmNews.setArticleId((Long)data);
        updateWmNews(wmNews,(short)9,"文章审核通过");
    }
    @Autowired
    private AdChannelMapper adChannelMapper;

    @Autowired
    ArticleFeign articleFeign;

    //保存app文章
    private ResponseResult saveArticle(WmNews wmNews){
        ArticleDto articleDto = new ArticleDto();
        // 如果文章ID存在则执行修改操作
        if (wmNews.getArticleId() != null){
            articleDto.setId(wmNews.getArticleId());
        }
        BeanUtils.copyProperties(wmNews, articleDto);

        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());
        //设置频道
        AdChannel channel = adChannelMapper.selectById(wmNews.getChannelId());
        if (channel != null){
            articleDto.setChannelId(((AdChannel) channel).getId());
            articleDto.setChannelName(channel.getName());
        }
        //设置作者信息
        WmUser wmUser = wemediaFeign.findWmUserById(wmNews.getUserId());
        articleDto.setAuthorName(wmUser.getName());
        // 文章内容
        articleDto.setContent(wmNews.getContent());

        return articleFeign.saveArticle(articleDto);
    }
}
















